package com.xiaobai.java_core.io;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author wangtw
 * @Description 数据分包
 * @Date 21:52 2024/11/5
 **/
public class DataPacking {

    public static void main(String[] args) throws IOException {
        // 分包
        File inputFile = new File("input.txt");
        File outputDir = new File("output_dir");
        splitFileIntoPackages(inputFile, outputDir, 1024 * 1024); // 每个包1MB

        // 合包
        File mergedFile = new File("merged.txt");
        mergePackagesIntoFile(outputDir, mergedFile);
    }

    public static void splitFileIntoPackages(File inputFile, File outputDir, int packageSize) throws IOException {
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }

        try (FileInputStream fis = new FileInputStream(inputFile);
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            byte[] buffer = new byte[packageSize];
            int bytesRead;
            int packageCount = 0;
            while ((bytesRead = bis.read(buffer)) != -1) {
                // 写入输出文件
                String packageName = "package_" + (++packageCount);
                File outputFile = new File(outputDir, packageName);
                try (FileOutputStream fos = new FileOutputStream(outputFile);
                     BufferedOutputStream bos = new BufferedOutputStream(fos)) {
                    bos.write(buffer, 0, bytesRead);
                }
            }
        }
    }

    public static void mergePackagesIntoFile(File inputDir, File outputFile) throws IOException {
        if (!inputDir.isDirectory()) {
            throw new IllegalArgumentException("Input directory is not a directory.");
        }

        try (FileOutputStream fos = new FileOutputStream(outputFile);
             BufferedOutputStream bos = new BufferedOutputStream(fos)) {
            File[] packageFiles = inputDir.listFiles((dir, name) -> name.startsWith("package_"));
            for (File packageFile : packageFiles) {
                try (FileInputStream fis = new FileInputStream(packageFile);
                     BufferedInputStream bis = new BufferedInputStream(fis)) {
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = bis.read(buffer)) != -1) {
                        bos.write(buffer, 0, bytesRead);
                    }
                }
            }
        }
    }
}
